import { Component, OnInit, Injector, ViewChild, ElementRef } from '@angular/core';
import { AdminModel, AdminService } from '../services/admin.service';
import { DetailBase } from 'app/modules/base/detail-base';
import { Validators } from '@angular/forms';
import {
  markAllAsTouched,
  formGroupToFormData,
  confirmPassword,
  firstInvalid,
} from 'app/modules/base/helper';
import { BehaviorSubject } from 'rxjs';
import { toTree } from 'app/modules/share/components/tree/tree.component';
import { LoginService } from 'app/modules/login/services/login.service';
import { switchMap } from 'rxjs/operators';
import { ZoneService } from 'app/modules/zone/services/zone.service';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'm-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss'],
})
export class DetailComponent extends DetailBase implements OnInit {
  treeData: any;
  id
  @ViewChild('body') body: ElementRef;
  constructor(
    private inject: Injector,
    public zoneService: ZoneService,
    private adminManager: AdminService,
    private loginService: LoginService,
    public http: HttpClient,
  ) {
    super(inject);


    this.route.queryParams.subscribe((params: any) => {
      this.id = params.id;
      this.http.get('api/admin/batch_areas', { params: { limit: '50', admin_id: this.id } }).subscribe((res: any) => {
        this.treeData = res.message;
      });
    });
  }
  form = this.fb.group({
    id: [0, Validators.required],
    username: ['', Validators.required],
    full_name: ['', Validators.required],
    phone: [''],
    email: ['', Validators.email],
    photo: [''],
    remark: [''],
    area_ids: [[]],
    auth_ids: [[]],
  });


  resetPwdForm = this.fb.group(
    {
      id: [0, Validators.required],
      login_password: ['', Validators.required],
      password: ['', Validators.required],
      confirm: ['', Validators.required],
    },
    {
      validators: [confirmPassword()],
    },
  );

  admin_info$ = this.getData<AdminModel>('data');
  departments$ = new BehaviorSubject<any>([]);
  admin_zones$ = this.admin_info$.pipe(
    switchMap(async admin_info => {
      let result = await this.zoneService.list();
      if (admin_info.area_ids && admin_info.area_ids.length) {
        result.list = result.list.filter((item) => { return admin_info.area_ids.includes(item.id); });
      }
      const tree = toTree(result.list, 'level_struct');
      this.departments$.next(tree)
      return tree
    }),
  );
  admin_auth$ = this.admin_info$.pipe(
    switchMap(async admin_info => {
      if (admin_info.auth_ids) {
        return admin_info.auth_ids;
      }
      const list = await this.adminManager.auth_nodes().toPromise();
      return list.map(auth => auth.id);
    }),
  );

  user$ = this.loginService.User$;
  not_self$ = this.user$.pipe(
    switchMap(() => this.admin_info$, (user, admin_info) => user.username !== admin_info.username),
  );
  editing = false;

  ngOnInit() {
    this.admin_info$.subscribe(info => {
      this.form.patchValue(info);
      this.resetPwdForm.patchValue(info);
    });
  }

  srocllTop(e) {
    this.body.nativeElement.scrollTop = e;
  }


  async submit() {
    markAllAsTouched(this.form);
    if (this.form.invalid) {
      return;
    }
    const data = formGroupToFormData(this.form);
    await this.adminManager.update(data);
    this.toaster.success('保存成功');
    this.reload();
    this.http.get('api/admin/batch_areas', { params: { limit: '50', admin_id: this.id } }).subscribe((res: any) => {
      this.treeData = res.message;
    });
    this.editing = false;
  }

  async delete(admin_info: AdminModel) {
    const result = await this.sweet.confirm(`确定要删除${admin_info.full_name}吗？`);
    if (result.dismiss) {
      return;
    }
    await this.adminManager.delete([admin_info.id]);
    this.toaster.success('删除成功');
    this.back();
  }

  async resetPwd() {
    markAllAsTouched(this.resetPwdForm);
    if (this.resetPwdForm.invalid) {
      return;
    }
    const value = this.resetPwdForm.value;
    try {

      let data = {
        id: value.id,
        login_password: window['HACKER'].aes128(value.login_password),
        new_password: window['HACKER'].aes128(value.password),
      }
      // 

      await this.adminManager.reset_password(data);
      this.toaster.success('重置密码成功');
      this.dialog.closeAll();
    } catch (err) {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          this.resetPwdForm.get('login_password').setErrors({ password: true });
        }
      }
    }
  }
}
